﻿
namespace Huirui.Cavan.Presentation.Seedwork
{
    using System;
    using System.Collections.Generic;
    using Huirui.Cavan.Core.Persistent;

    public class PagedList<T> : List<T>, ISearch
    {
        IDictionary<string, bool> _orderBy = new Dictionary<string, bool>();

        public PagedList(IList<T> items, int pageIndex, int pageSize)
        {
            MaxRowsPerPage = pageSize;
            TotalItemCount = items.Count;
            CurrentPage = pageIndex;
            for (int i = StartRecordIndex - 1; i < EndRecordIndex; i++)
            {
                Add(items[i]);
            }
        }

        public PagedList(IEnumerable<T> items, int pageIndex, int pageSize, int totalItemCount)
        {
            AddRange(items);
            TotalItemCount = totalItemCount;
            CurrentPage = pageIndex;
            MaxRowsPerPage = pageSize;
        }

        public virtual long TotalRowCount { get; set; }

        public virtual int MaxRowsPerPage { get; set; }

        public virtual int CurrentPage { get; set; }

        public virtual long PageCount
        {
            get { return (TotalRowCount - 1) / MaxRowsPerPage; }
        }

        /// <summary>
        ///     Tricky collection allowing sorting. 
        ///     If the implementing collection is Dictionary[string, bool]
        ///     then even the position plays role.
        ///     The first added as firstly evaluated in the ORDER BY clause.
        /// </summary>
        public virtual IDictionary<string, bool> OrderBy
        {
            get { return _orderBy; }
            set { _orderBy = value; }
        }

        public int TotalItemCount { get; set; }
        public int TotalPageCount { get { return (int)Math.Ceiling(TotalItemCount / (double)MaxRowsPerPage); } }
        public int StartRecordIndex { get { return (CurrentPage - 1) * MaxRowsPerPage + 1; } }
        public int EndRecordIndex { get { return TotalItemCount > CurrentPage * MaxRowsPerPage ? CurrentPage * MaxRowsPerPage : TotalItemCount; } }
        public int CurrentRow { get; set; }
        public string Sql { get; set; }
        public string CorporationCode { get; set; }
        public bool RelateCorporation { get; set; }
    }
}
